//
//  YWLogRecordTool.m
//  maintain
//
//  Created by 烟雨云渊 on 17/2/14.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWLogRecordTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "WMHttpTool.h"
#import "YWCommonTool.h"
#import "SSZipArchive.h"
#import <AliyunOSSiOS/OSSService.h>

@interface YWLogRecordTool()
@property (nonatomic,strong) dispatch_queue_t concurrentWriteFileQueue;//自己创建的线程
@property (nonatomic, strong) NSFileManager* fileManager;
@property (nonatomic, strong) OSSClient* ossClient;
@end

@implementation YWLogRecordTool
YWSingletonM(LogRecordManager)

- (NSFileManager*)fileManager
{
    if (!_fileManager) {
        _fileManager = [NSFileManager defaultManager];
    }
    return _fileManager;
}

- (dispatch_queue_t)concurrentWriteFileQueue{
    if (!_concurrentWriteFileQueue) {
        _concurrentWriteFileQueue = dispatch_queue_create("logRecordToolQueue", DISPATCH_QUEUE_CONCURRENT);
    }
    return _concurrentWriteFileQueue;
}

- (OSSClient*)ossClient
{
    if (!_ossClient) {
        id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:kAliyunAccessKey secretKey:kAliyunSecretKey];
        
        OSSClientConfiguration* conf = [OSSClientConfiguration new];
        conf.maxRetryCount = 3;
        conf.enableBackgroundTransmitService = NO;
        conf.timeoutIntervalForRequest = 15;
        conf.timeoutIntervalForResource = 24 * 60 * 60;
        
        self.ossClient = [[OSSClient alloc] initWithEndpoint:kAliyunEndPoint credentialProvider:credential clientConfiguration:conf];
    }
    return _ossClient;
}

- (NSMutableDictionary*)getLogDictionaryWithModule:(NSString*)module interface:(NSString*)url params:(NSDictionary*)params headers:(NSDictionary*)headers tag:(NSString*)tag{
    NSMutableDictionary * logDic = [NSMutableDictionary dictionary];
    [logDic setValue:module?:@"无" forKey:@"module"];
    [logDic setValue:url?:@"无" forKey:@"interface"];
    [logDic setValue:params?:@"无" forKey:@"params"];
    [logDic setValue:headers?:@"无" forKey:@"headers"];
    [logDic setValue:tag?:@"无" forKey:@"tag"];
    return logDic;
}

- (NSMutableDictionary *)successOrFailedLogDicWith:(NSMutableDictionary *)dic statusCode:(NSInteger)statusCode errorInfo:(NSString *)errorInfo logTag:(NSString *)logTag{
    NSMutableDictionary * logDic = dic ? dic : [NSMutableDictionary dictionary];
    [logDic setValue:@(statusCode) forKey:@"statusCode"];
    [logDic setValue:errorInfo?:@"无" forKey:@"result"];
    [logDic setValue:logTag?:@"无" forKey:@"requestBackTag"];
    return logDic;
}

- (void)saveLocalPatameterLog:(NSDictionary *)logDic{
    dispatch_barrier_async(self.concurrentWriteFileQueue, ^{
        NSData *data =    [NSJSONSerialization dataWithJSONObject:logDic options:NSJSONWritingPrettyPrinted error:nil];
        NSString * logName = [self logName];
        [self saveDataToCacheStorage:data withResourcePath:logName];
    });
}

- (NSString*)saveDataToCacheStorage:(NSData*)data withResourcePath:(NSString*)fileName
{
    BOOL ret = NO;
    if (!data || !fileName.length) {
        return nil;
    }
    NSString* cachePath = [self cachePathFromResourcePath:fileName];
    NSString* tmp = [cachePath stringByDeletingLastPathComponent];
    NSError* error = nil;
    if (![self.fileManager fileExistsAtPath:tmp]) {
        ret = [self.fileManager createDirectoryAtPath:tmp withIntermediateDirectories:YES attributes:nil error:&error];
        if (ret) {
            ret = [data writeToFile:cachePath atomically:YES];
        }
    }
    else {
        //当没有那个路径的时候就创建，并保存
        if (![self.fileManager fileExistsAtPath:cachePath]) {
            ret = [data writeToFile:cachePath atomically:YES];
        }else{
            NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:cachePath];
            
            [fileHandle seekToEndOfFile];  //将节点跳到文件的末尾
            [fileHandle writeData:data];//追加写入数据
            [fileHandle closeFile];
            ret = YES;
        }
    }
    return ret ? cachePath : nil;
}

- (NSString*)cachePathFromResourcePath:(NSString*)fileName{
    NSString* cachePath = nil;
    
    NSString* rootPath = [[self cachePathFromResourcePath] stringByAppendingPathComponent:@"localParameterLogs"];
    
    cachePath = [[rootPath stringByAppendingPathComponent:fileName] stringByAppendingPathComponent:cachePath];
    
    return cachePath;
}

- (NSString*)cachePathFromResourcePath{
    static NSString* path = nil;
    if (!path) {
        //cache folder
        path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        //create the folder if it doesn't exist
        if (![self.fileManager fileExistsAtPath:path isDirectory:NULL]) {
            [self.fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:NULL];
        }
    }
    return path;
}

//判断是否存在log日志
- (BOOL)existLogRecordFile{
    NSString * filePath = [self filePath];
    return [self.fileManager fileExistsAtPath:filePath];
}

//上传log日志
- (void)uploadLogRecordToAliyunOSSProgressBlock:(void (^)(float progress))progressBlock completeBlock:(void (^)(BOOL success))completeBlock{
        NSString * zipFilePath = [self zipFilePath];
    dispatch_barrier_async(self.concurrentWriteFileQueue, ^{
        if ([self.fileManager fileExistsAtPath:zipFilePath]){
            [self uploadLogRecordSyncWithFilePath:zipFilePath progressBlock:^(float progress) {
                if (progressBlock) {
                    progressBlock(progress);
                }
            } completeBlock:^(BOOL success) {
                if (completeBlock) {
                    [self deleteLogFile];
                    completeBlock(success);
                }
            }];
        }else{
            completeBlock(NO);
            YWLog(@"文件路径不存在！");
        }
    });
}

- (void)uploadLogRecordSyncWithFilePath:(NSString*)filePath progressBlock:(void (^)(float))progressBlock completeBlock:(void (^)(BOOL success))completeBlock{
    OSSPutObjectRequest* put = [OSSPutObjectRequest new];
    put.bucketName = kAliyunbucketName;
    put.objectKey = [NSString stringWithFormat:@"app-log/iOS/%@",[filePath lastPathComponent]];
    put.uploadingFileURL = [NSURL fileURLWithPath:filePath];
    
    // optional fields
    if (progressBlock) {
        put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            progressBlock(totalByteSent*1.0/totalBytesExpectedToSend);
            YWLog(@"file %@: %lld, %lld, %lld", filePath, bytesSent, totalByteSent, totalBytesExpectedToSend);
        };
    }
    
    OSSTask* putTask = [self.ossClient putObject:put];
    [putTask waitUntilFinished];
    if (!putTask.error) {
        if (completeBlock) {
            //删除压缩文件
            [self deleteUserInfoFile:filePath];
            completeBlock(YES);
        }
    }
    else {
        YWLog(@"upload object failed, error: %@", putTask.error);
        if (completeBlock) {
            completeBlock(NO);
        }
    }
}

//日志存储名称
- (NSString*)logName{
    YWLoginUser * loginUser = [YWLoginTool loginUser];
    NSString *companyAccount = loginUser.companyAccount?:@"";
    NSString *userId = @(loginUser.uniqueId).stringValue;
    NSString *logName = [NSString stringWithFormat:@"%@_%@",companyAccount,userId];
    return logName;
}

//日志存储路径
- (NSString*)filePath{
    NSString *fileName = [self logName];
    NSString * filePath = [self cachePathFromResourcePath:fileName];
    return filePath;
}

//压缩文件
- (NSString*)zipFilePath{
    NSString * zipFileName = [self zipFileName];
    NSString * zipFilePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:zipFileName];
    NSString * unzipFilePath = [self filePath];
    BOOL successZip = [SSZipArchive createZipFileAtPath:zipFilePath withFilesAtPaths:@[ unzipFilePath ]];
    if (successZip) {
        //是否删除文件
        
    }else{
        
    }
    return zipFilePath;
}

//压缩文件名称
- (NSString*)zipFileName{
    YWLoginUser * loginUser = [YWLoginTool loginUser];
    NSString *companyAccount = loginUser.companyAccount?:@"";
    NSString *userId = @(loginUser.uniqueId).stringValue;
    NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
    NSString *time = [YWCommonTool showDateAndsecond:nowTime];
    //企业id_用户id_时间
    NSString * zipFileName = [NSString stringWithFormat:@"%@_%@_%@.zip",companyAccount,userId,time];
    return zipFileName;
}

//删除压缩文件
- (void)deleteUserInfoFile:(NSString*)filePath{
    dispatch_barrier_async(self.concurrentWriteFileQueue, ^{
        BOOL deleSuccess = [self.fileManager removeItemAtPath:filePath error:nil];
        if (deleSuccess) {
            YWLog(@"删除压缩文件成功");
        }else{
            YWLog(@"删除压缩文件不成功");
        }
    });
}
//返回日志文件的大小
- (NSString*)logFileSize{
    NSString * filePath = [self filePath];
    CGFloat fileSize;
    if ([self.fileManager fileExistsAtPath:filePath]){
        unsigned long long length  = [[self.fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
        fileSize = length; //换算成多少b(*1024.0)
    }else{
        fileSize = 0;
    }
    NSString * size = [YWCommonTool getFileSize:fileSize];
    return size;
}

//删除日志文件
- (void)deleteLogFile{
    NSString * logFilePath = [self filePath];
    if ([self.fileManager fileExistsAtPath:logFilePath]){
        dispatch_barrier_async(self.concurrentWriteFileQueue, ^{
        BOOL deleSuccess = [self.fileManager removeItemAtPath:logFilePath error:nil];
            if (deleSuccess) {
                YWLog(@"删除日志文件成功");
            }else{
                YWLog(@"删除日志文件不成功");
                }
            });
        }
}

@end
